import traceback
from flask import Blueprint,request
from sqlalchemy import func, and_
import  models
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from config import  log as log
from config import makeNewSession as makeNewSession

classes = Blueprint('classes',__name__)


###### 班级表

# 添加班级
@classes.route("/addClassesData", methods=["POST"])
def addClassesData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    if not isinstance(getData["classesID"], int): getData["classesID"] = int(getData["classesID"])
    session = makeNewSession()

    try:
        q = session.query(models.Group).filter(models.Group.gid==int(getData['mainGroup'])).first()
        # print("add classes q", q)
        if q:
            # del getData['mainGroup']
            obj = models.Classes(**getData, cls_group=q)
        else:
            q = models.Group(gid=int(getData['mainGroup']))
            # del getData['mainGroup']
            obj = models.Classes(**getData, cls_group=q)
        print("obj",obj.to_json())
        session.add(obj)
        session.commit()
        session.close()
        return "add classes successfully"
    except:
        print(getData,"插入数据库失败")
        traceback.print_exc()
        session.rollback()
        session.close()
        return ("add classes failure",500)

# 添加班级 多个
@classes.route("/addmClassesData",methods=["POST"])
def addmClassesData():
    getDatas = request.get_json()
    session = makeNewSession()
    for data in getDatas:
        try:
            obj = models.Classes(**data)
            session.add(obj)
            session.commit()
        except:
            print(data,"插入数据库失败")
            traceback.print_exc()
            session.rollback()
    
    session.close()
    return "add many classes successfully"



# 获取班级数据指定分页
@classes.route("/classesData")
def classesData():
    curPage = request.args.get("page",1,type=int)
    per_page = request.args.get("limit",15,type=int)
    getData = json.loads(request.args.get("searchParams","{}"))
    # print(getData, bool(getData),"text",getData)
    session = makeNewSession()
    if getData:
        condition = and_(
            models.Classes.classesID.contains(getData.get("classesID",0)),
            models.Classes.mainGroup.contains(getData.get("mainGroup",0)),
            models.Classes.beizhu.contains(getData.get("beizhu",''))
        )

    # 分页
    all_ = session.query(models.Classes).offset((curPage-1)*per_page).limit(per_page)   if not getData else session.query(models.Classes).filter(condition).offset((curPage-1)*per_page).limit(per_page)  

    # count  = session.query(func.count(all_)).scalar()
    # 获取总条数
    count =session.query(func.count(models.Classes.classesID)).scalar() if not getData else session.query(func.count(models.Classes.classesID)).filter(condition).scalar()


    result = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
        }
    for each in all_:
        each = each.to_json()
        result['data'].append(each)
    # print(each)
    result = json.dumps(result,ensure_ascii=False)
    session.close()
    return result


# 删除班级数据
@classes.route("/delClassesData",methods=["POST"])
def delClassesData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    session = makeNewSession()
    try:

        session.query(models.Classes).filter(models.Classes.classesID==getData['classesID']).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500
# 删除班级数据 多条
@classes.route("/delmClassesData",methods=["POST"])
def delmClassesData():
    getDatas = request.get_json()
    print("getDatas",getDatas)
    session = makeNewSession()
    try:
        session.query(models.Classes).filter(models.Classes.classesID.in_(getDatas)).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500
# 更新班级数据
@classes.route("/updateClassesData",methods=["POST"])
def updateClassesData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    print(getData)
    session = makeNewSession()
    try:
        session.query(models.Classes).filter(models.Classes.classesID==getData["classesID"]).update(getData)
        session.commit()
        session.close()
        return "update successfully"
    except:
        session.rollback()
        session.close()
        return "update failure",500

